<template>
  <div style="width:100%">
    <el-tag
      :key="index"
      v-for="(tag, index) in dynamicTags"
      :closable="mixEditable"
      :disable-transitions="false"
      size="medium"
      @close="handleClose(tag)">
      <span @dblclick="editTag(tag, index)" style="cursor: pointer;">
        {{tag}}
      </span>
    </el-tag>
    <el-input
      v-if="inputVisible"
      v-model="inputValue"
      ref="saveTagInput"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
      style="width: 150px;margin-top: 8px;"
    >
    </el-input>
    <el-button v-else size="mini" type="primary" :disabled="!mixEditable" plain @click="showInput">+ 添加自定义标签</el-button>
  </div>
</template>
<script>
export default {
  name: 'indicators',
  props: {
    value: '',
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
  },
  computed: {
    isDesigner(){
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
    tags() {
      return this.options.filter(o => this.value && this.value.split(',').some(v => v === o.id))
    },
   
  },
  data() {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      isEdit: false,
      editIndex: 0
    }
  },
  created(){
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (val) {
          this.dynamicTags = val.split(',')
        } else {
          this.dynamicTags = []
        }
      }
    }
  },
  methods: {
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      this.$emit('input', this.dynamicTags.join(','))
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        if (this.isEdit) {
          this.isEdit = false
          this.dynamicTags[this.editIndex] = inputValue
        } else {
          this.dynamicTags.push(inputValue);
          this.$emit('input', this.dynamicTags.join(','))
        }
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    editTag(tag, index) {
      if (this.mixEditable) {
        this.inputVisible = true
        this.isEdit = true
        this.editIndex = index
        this.inputValue = tag
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .el-tag {
    margin-right: 10px;
    margin-top: 10px;
  }
</style>